package cn.xzsyzjc.controller;


import cn.xzsyzjc.error.BusinessException;
import cn.xzsyzjc.error.EmBusinessError;
import cn.xzsyzjc.response.CommonReturnType;
import cn.xzsyzjc.service.OrderService;
import cn.xzsyzjc.service.UserService;
import cn.xzsyzjc.service.model.OrderModel;
import cn.xzsyzjc.service.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: miaosha
 * @description: 下单
 * @author: wyh
 * @create: 2019-01-21 23:13
 **/

@Controller("order")
@RequestMapping("/order")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    //封装下单请求
    @RequestMapping(value = "/createorder",method = RequestMethod.POST)
    @ResponseBody
    public CommonReturnType createOrder(@RequestParam(name = "itemId")Integer itemId,
                                        @RequestParam(name = "promoId",required = false)Integer promoId,
                                        @RequestParam(name = "amount")Integer amount) throws BusinessException {

        Boolean isLogin = (Boolean) httpServletRequest.getSession().getAttribute("IS_LOGIN");
        if(isLogin == null || !isLogin.booleanValue()){
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN,"用户还未登录，不能下单");
        }

        //获取用户的登录信息
        UserModel userModel = (UserModel) httpServletRequest.getSession().getAttribute("LOGIN_USER");

        OrderModel orderModel = orderService.createOrder(userModel.getId(),itemId,promoId,amount);
        return CommonReturnType.create(null);
    }

    @RequestMapping(value = "/get")
    @ResponseBody
    public String generateNo(){
        String result = orderService.generateOrderNo();
        return result;
    }
}
